
import { ArrowLeft } from '@nutui/icons-react'
import styles from './VerifyCode.module.css'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import React from 'react';
import { Notify, PasswordInput, ConfigProvider, Button, CountDown } from 'react-vant';
import { http } from '../../utils'
const VerifyCode = () => {
    const navigate = useNavigate();
    const location = useLocation()
    const UpdateRef = useRef()
    const [loginCode, setLoginCode] = useState()
    const [inputLoginCode,setInputLoginCode] = useState()
    const [isShowCount, setIsShowCount] = useState(true)
    const [countTime, setCountTime] = useState(60)
    const getVerifyPhone = useMemo(() => {
        let str = ''
        str += location.state.value.slice(0, 3)
        str += '****'
        str += location.state.value.slice(7)
        return str
    })

    const handleGetCode = async () => {
        try {
            const response = await http.post('/main/getCode', { phoneNumber: location.state.value });
            if (response.code == 200) {
                setLoginCode(response.phoneCode)
            }
        } catch (error) {
            console.error('Error sending verification code:', error);
        }
    };

    useEffect(() => {
        if (!UpdateRef.current) {
            UpdateRef.current = true
            handleGetCode()
            onSetInterval()
        }
    }, [])

    const onSetInterval = () => {
        let timeFun = setInterval(() => {
            setCountTime(prevTime => {
                const newTime = prevTime - 1;
                if (newTime === 0) {
                    clearInterval(timeFun);
                    setIsShowCount(false)
                    setLoginCode('')
                }
                return newTime;
            });
        }, 1000)
    }

    const onClickGetCode = () => {
        setCountTime(60)
        setIsShowCount(true)
        onSetInterval()
        handleGetCode()
    }

    const onSubmitLogin = async () => {
        if(!loginCode){
            Notify.show({ type: 'warning', message: '验证码未填写' })
            return
        }
        if(!loginCode && !isShowCount){
            Notify.show({ type: 'warning', message: '验证码过期，请重新发送' })
            setInputLoginCode('')
            return
        }
        if(inputLoginCode == loginCode){
            let res = await http.post('/main/subLogin', { phone: location.state.value })
            if(res.code == 200){
                // navigate('')
                console.log('登录成功');
            }else{
                Notify.show({ type: 'warning', message: '服务器繁忙' })
            }
        }else{
            setInputLoginCode('')
            Notify.show({ type: 'danger', message: '验证码错误，请重新输入' })
        }
        
    }

    const themeVars = {
        passwordInputBackgroundColor: "#f7f7f7"
    }
    return (
        <ConfigProvider themeVars={themeVars}>
            <div className={styles.verify_out_box}>
                <div className={styles.verify_ArrowLeft_box}><ArrowLeft onClick={() => { navigate(-1) }} /></div>
                <p className={styles.verify_title_p}>
                    我们将以短信或电话的形式，把验证码发送至{getVerifyPhone}，请留意手机短信，或接听0755 / 0766 / 025 / 010等开头的电话。
                </p>
                <div className={styles.verify_passInput_box}>
                    <PasswordInput
                        // onSubmit={onSubmit}
                        autoFocus
                        gutter='0.02rem'
                        mask={false}
                        onChange={((val)=>{
                            setInputLoginCode(val)
                        })}
                        value={inputLoginCode}
                        info={
                            <p
                                style={{ textAlign: 'left', fontSize: '0.16rem', lineHeight: '0.2rem' }}
                            >
                                {
                                    isShowCount ?
                                        <>
                                            重新发送{countTime} 秒
                                        </> :
                                        <>
                                            <span style={{ color: 'red', }} onClick={() => { onClickGetCode() }}>获取验证码</span>
                                        </>
                                }
                            </p>
                        }
                    />
                </div>
                <Button
                    round
                    type='primary'
                    block
                    color={'linear-gradient(to right, #ff9600 , #fe4801)'}
                    onClick={() => onSubmitLogin()}
                >
                    登录
                </Button>
            </div>
        </ConfigProvider>

    )
}
export default VerifyCode